package com.logic.landseaserver.service.impl;

import java.util.Date;
import java.util.List;

import com.logic.landseaserver.service.Action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.logic.common.exception.BusinessException;
import com.logic.common.security.SecurityUtils;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.enums.PropertyStatusEnum;
import com.logic.landseaserver.common.exception.LandseaBusinessException;
import com.logic.landseaserver.domain.Property;
import com.logic.landseaserver.domain.PropertyCheck;
import com.logic.landseaserver.domain.PropertyCheckActionLogs;
import com.logic.landseaserver.domain.PropertyCheckEstimation;
import com.logic.landseaserver.persistence.read.PropertyCheckActionLogsReadMapper;
import com.logic.landseaserver.persistence.read.PropertyCheckEstimationReadMapper;
import com.logic.landseaserver.persistence.read.PropertyCheckReadMapper;
import com.logic.landseaserver.persistence.read.PropertyReadMapper;
import com.logic.landseaserver.persistence.write.PropertyCheckActionLogsWriteMapper;
import com.logic.landseaserver.persistence.write.PropertyCheckEstimationWriteMapper;
import com.logic.landseaserver.persistence.write.PropertyCheckWriteMapper;
import com.logic.landseaserver.service.IPropertyCheckService;
import com.logic.landseaserver.ws.dto.LogsDTO;
import com.logic.landseaserver.ws.dto.PropertyCheckDTO;
import com.logic.landseaserver.ws.dto.PropertyCheckEstimationDTO;
import com.logic.landseaserver.ws.dto.PropertyCheckLogDTO;
import com.logic.landseaserver.ws.request.PropertyCheckDeleteReq;
import com.logic.system.domain.SystemFile;
import com.logic.system.service.IFileService;
import com.logic.system.ws.dto.FileConverter;


@Service
public class PropertyCheckServiceImpl implements IPropertyCheckService {

    @Autowired
    private PropertyCheckWriteMapper propertyCheckWriteMapper;
    @Autowired
    private IFileService fileService;

    @Autowired
    private PropertyCheckReadMapper propertyCheckReadMapper;

    @Autowired
    private PropertyCheckEstimationWriteMapper propertyCheckEstimationWriteMapper;

    @Autowired
    private PropertyCheckEstimationReadMapper propertyCheckEstimationReadMapper;

    @Autowired
    private PropertyCheckActionLogsWriteMapper propertyCheckActionLogsWriteMapper;

    @Autowired
    private PropertyCheckActionLogsReadMapper propertyCheckActionLogsReadMapper;

    @Autowired
    private PropertyReadMapper propertyReadMapper;

    @Override
    public void delete(String arg0) throws BusinessException {
        // TODO Auto-generated method stub

    }

    @Override
    public Object get(Integer arg0) throws BusinessException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int insert(Object arg0) throws BusinessException {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public List<?> query(QueryUtil arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void update(Object arg0) throws BusinessException {
        // TODO Auto-generated method stub

    }

    @Override
    public Boolean validate(Object arg0) throws BusinessException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Boolean validateForDelete(Object arg0) throws BusinessException {
        return null;
    }

    @Override
    public Boolean validateForInsert(Object arg0) throws BusinessException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Boolean validateForUpdate(Object arg0) throws BusinessException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    @Action(name = "上传测算表")
    public int insertPropertyCheck(PropertyCheck propertyCheck) throws LandseaBusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        if (propertyCheck.getPropertyId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CHECK_PROPERTY_ID_IS_NULL);
        }
        //判断物业是否合法
        checkTheProperty(propertyCheck.getPropertyId());
        if (StringUtils.isEmpty(propertyCheck.getEstimationName())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CHECK_FILENAME_ID_IS_NULL);
        }
        if (propertyCheck.getEstimationTableId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CHECK_FILE_ID_IS_NULL);
        }
        propertyCheck.setEstimationVerison(propertyCheckReadMapper.getMaxVersion(propertyCheck.getPropertyId()));
        propertyCheck.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
        propertyCheckWriteMapper.insertSelective(propertyCheck);
        int id = propertyCheck.getId();
        return id;
    }

    @Override
    public List<PropertyCheckDTO> queryByPage(QueryUtil queryUtil, Integer propertyId) throws BusinessException {
        queryUtil.getParams().put("userId", SecurityUtils.getCurrentLogin().getUserId());
        queryUtil.getParams().put("propertyId", propertyId);
        List<PropertyCheckDTO> dtoList = propertyCheckReadMapper.selectByPage(queryUtil);
        for (int i = 0; dtoList.size() > 0 && i < dtoList.size(); i++) {
            PropertyCheckDTO dto = dtoList.get(i);
            dto.setFile(FileConverter.fromFileToDTO((SystemFile) this.fileService.get(dto.getEstimationTableId())));
        }
        return dtoList;
    }

    @Override
    @Action(name="添加审查记录")
    public int insertCheckResult(PropertyCheckEstimation propertyCheckEstimation) throws LandseaBusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        if (propertyCheckEstimation.getPropertyId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_PROPERTY_ID_IS_NULL);
        }
        //判断物业是否合法
        checkTheProperty(propertyCheckEstimation.getPropertyId());
        if (propertyCheckEstimation.getPropertyCheckId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CHECK_ESTIMATION_ID_IS_NULL);
        }

        if (StringUtils.isEmpty(propertyCheckEstimation.getEstimationResultCode())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CHECK_RESULT_IS_NULL);
        }
        if (StringUtils.isEmpty(propertyCheckEstimation.getEstimationRole())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CHECK_ROLE_IS_NULL);
        }
        if (StringUtils.isEmpty(propertyCheckEstimation.getEstimateName())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_CHECK_NAME_IS_NULL);
        }

        propertyCheckEstimation.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
        propertyCheckEstimationWriteMapper.insert(propertyCheckEstimation);
        int id = propertyCheckEstimation.getId();
        return id;
    }


    private void checkTheProperty(Integer propertyId) throws LandseaBusinessException {
        Property property = propertyReadMapper.selectByPrimaryKey(propertyId);
        if (property == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_REPORT_IS_NULL);
        }
        //是否处于审批阶段
        if (!property.getStatus().equals(PropertyStatusEnum.PS2.toString())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_IS_NO_PS3);
        }
        //判断是否中止
        if (property.getIsSuspend()) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_IS_SUSPEND);
        }

    }

    @Override
    public List<PropertyCheckEstimationDTO> getCheckResults(Integer propertyCheckId) throws LandseaBusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        List<PropertyCheckEstimationDTO> dtoList = propertyCheckEstimationReadMapper.selectAllCheckEstimation(propertyCheckId);
        return dtoList;
    }

    @Override
    public void insertLog(LogsDTO log) throws LandseaBusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        if (log.getPropertyCheckId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_ACTIONLOG_FKID_NULL);
        }

        if (StringUtils.isEmpty(log.getActionUser())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_ACTIONLOG_OPR_NULL);
        }

        if (StringUtils.isEmpty(log.getAction())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_ACTIONLOG_OPRACTION_NULL);
        }

        if (log.getModules() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_ACTIONLOG_MODULE_NULL);
        }
        PropertyCheckActionLogs actionLog = new PropertyCheckActionLogs();
        actionLog.setPropertyCheckId(log.getPropertyCheckId());
        actionLog.setAction(log.getAction());
        actionLog.setActionDate(new Date());
        actionLog.setActionUser(log.getActionUser());
        actionLog.setModules(log.getModules());
        actionLog.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
        propertyCheckActionLogsWriteMapper.insert(actionLog);
    }

    @Override
    public List<PropertyCheckLogDTO> getRecords(Integer propertyCheckId, Integer modules) {
        List<PropertyCheckLogDTO> list = propertyCheckActionLogsReadMapper.getRecords(propertyCheckId, modules);
        return list;
    }

    @Override
    @Action(name="删除测算表")
    public void deletePropertyChecks(PropertyCheckDeleteReq req) throws LandseaBusinessException {
        if (req.getPropertyId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_PROPERTY_ID_IS_NULL);
        }
        checkTheProperty(req.getPropertyId());
        if (StringUtils.isEmpty(req.getPropertyCheckIds())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_DELETE_ID_IS_NULL);
        }

        String[] ids = req.getPropertyCheckIds().split(",");
        for (int i = 0; i < ids.length; i++) {
            if (!StringUtils.isEmpty(ids[i])) {
                PropertyCheck propertyCheck = new PropertyCheck();
                propertyCheck.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
                propertyCheck.setDeleted(true);
                propertyCheck.setId(Integer.parseInt(ids[i]));
                propertyCheckWriteMapper.updateByPrimaryKeySelective(propertyCheck);
            }

        }

    }

}
